﻿using Autofac;
using Loong.Dependency;
using Loong.Modules;
using Loong.Threading.BackgroundWorkers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Loong.Redis
{
    public sealed class RedisModule : Module, ILoongModule
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<RedisOptions>(configuration.GetSection(RedisOptions.SectionName));
        }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyByConvention(ThisAssembly);
        }

        public void Initialize()
        {
            using (var scope = IocManager.IocContainer.BeginLifetimeScope())
            {
                var options = scope.Resolve<IOptions<RedisOptions>>().Value;
                if (options.UseRedis)
                {
                    //scope.Resolve<RedisManager>().InitConfigAsync().Wait();
                    scope.Resolve<IBackgroundWorkerManager>().Add(scope.Resolve<RewriteAofWorker>());
                }
            }
        }

        public void Shutdown()
        {
            using (var scope = IocManager.IocContainer.BeginLifetimeScope())
            {
                scope.Resolve<RedisManager>().Dispose();
            }
        }
    }
}
